<script setup>
import {onMounted, ref} from "vue";
import DialogBox from "../DialogBox.vue";
import AgentDatabaseSetting from "./AgentDatabaseSetting.vue";
import api from "../../libs/api.js";
import {MdPreview} from "md-editor-v3";
import 'md-editor-v3/lib/style.css';

const props = defineProps({
  agent: {
    type: Object,
    required: true,
    default: () => ({
      id: null,
      name: '',
      agentType: '',
      note: '',
      icon: ''
    })
  }
});
const showTab = ref('text');
const showSetting = ref(false);
const databaseSettingRef = ref(null);

const from = ref({
  query: ''
})

const result = ref({
  id: 0,
  agentId: props.agent.id,
  think: '',
  text: '查询结果的文字总结内容将显示在这里...',
  querySql: '',
  queryName: '',
  table: {
    columns: ['表格结果'],
    rows: [['查询到的表格结果将显示在这里...']]
  }
});
const uuid = () => {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
};
const resultStatus = ref('think')
const canSave = ref(false);
const replyId = ref(uuid()); // 用于标识当前查询的回复ID

const executeQuery = (refresh) => {
  if (!from.value.query) {
    alert('请输入查询内容');
    return;
  }
  // 这里可以添加执行查询的逻辑
  const id = uuid(); // 更新回复ID
  replyId.value = id;
  console.log('Executing query:', from.value.query);
  // 例如，调用后端API获取查询结果
  // `/api/v1/agent/${props.agent.id}/database-query`
  // 流调用
  let token = localStorage.getItem('global_token');
  if (!token) {
    alert('请先登录');
    return;
  }
  token = JSON.parse(token).token;
  result.value.table.rows = [['正在查询,请稍后...']];
  result.value.table.columns = ['查询结果'];
  result.value.think = '';
  result.value.text = '';
  result.value.sql = '';
  canSave.value = false;
  let url = `/api/v1/agent/${props.agent.id}/database-query`;
  if (refresh) {
    url += '?refresh=true';
  }else{
    result.value.id = 0; // 重置ID以便新查询
    result.value.querySql = ''; // 清空之前的SQL查询
  }
  fetch(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}`
    },
    body: JSON.stringify({
      query: from.value.query,
      querySql: result.value.querySql
    })
  }).then(response => {
    const reader = response.body.getReader();
    const decoder = new TextDecoder('utf-8');
    return reader.read().then(function processText({ done, value }) {
      if (replyId.value !== id) {
        return; // 如果回复ID不匹配，说明查询已被取消
      }
      if (done) {
        console.log('Stream finished');
        canSave.value = true;
        return;
      }
      let allLine = decoder.decode(value);
      let lines = [allLine]
      if (allLine.concat('\n')){
        lines = allLine.split('\n');
      }
      for(let i in lines){
        let line = lines[i].trim();
        if (line === ''){
          continue;
        }
        if (line === '[DONE]'){
          return reader.read().then(processText);
        }
        if (line.startsWith("data:")){
          line = line.substring(5);
        }
        try {
          const json = JSON.parse(line);
          if (json.think){
            result.value.think += json.think;
            resultStatus.value = 'think';
          }
          if (json.content){
            result.value.text += json.content;
            resultStatus.value = 'text';
          }
          if (json.resultTable) {
            const table = JSON.parse(json.resultTable);
            result.value.table.columns = table.columnNames;
            result.value.table.rows = table.rows;
            console.log(result.value.table);
          }
          if (json.sql) {
            result.value.querySql = json.sql;
          }
        }catch (e){
          console.error('Error parsing JSON:', e, 'Line:', line);
          // 如果解析失败，可能是因为数据格式不正确或流中包含非JSON数据
          // 可以选择忽略此行或记录错误
          alert('发生错误, 请尝试重新查询');
        }
      }
      // Util.setLocalStorage("message_list_" + props.chat.id, messages.value)
      return reader.read().then(processText);
    });
  });
};

const saveQuery = () => {
  // `/api/v1/agent/${props.agent.id}/database-query/save`
  result.value.query = from.value.query;
  let defaultName = result.value.queryName || from.value.query;
  if (!defaultName) {
    defaultName = from.value.query.length > 10 ?
        from.value.query.toString().substring(0, 10) + '...' : from.value.query
  }
  result.value.queryName = prompt("请输入要保存的名称", defaultName);
  if (!result.value.queryName) {
    return;
  }
  api.post(`/api/v1/agent/${props.agent.id}/database-query/save`, result.value).then(res => {
    console.log('Query result saved:', res.data);
    alert('查询结果已保存');
    loadQueryRecord();
  });
};
const records = ref([]);
const loadQueryRecord = () => {
  api.get(`/api/v1/agent/${props.agent.id}/database-query/records`).then(res => {
    records.value = res.data.responseBody;
  }).catch(err => {
    console.error('Failed to load query records:', err);
  });
};
const selectQueryRecord = (record) => {
  if (result.value.id === record.id) {
    return; // 如果已选中则不做任何操作
  }
  result.value = {
    id:  record.id,
    agentId: props.agent.id,
    think: '',
    text: '查询结果的文字总结内容将显示在这里...',
    querySql: '',
    queryName: '',
    table: {
      columns: ['表格结果'],
      rows: [['查询到的表格结果将显示在这里...']]
    }
  }
  result.value.id = record.id;
  result.value.queryName = record.queryName;
  result.value.think = '';
  result.value.querySql = record.querySql;
  result.value.table = {
    columns: ['表格结果'],
    rows: [['查询到的表格结果将显示在这里...']]
  };
  from.value.query = record.query;
  canSave.value = true;
  executeQuery(true);
};

const deleteQueryRecord = (record) => {
  api.delete(`/api/v1/agent/${props.agent.id}/database-query/records/${record.id}`).then(res => {
    console.log('Query record deleted:', res.data);
    loadQueryRecord();
    if (result.value.id === record.id) {
      result.value = {
        id: 0,
        agentId: props.agent.id,
        think: '',
        text: '查询结果的文字总结内容将显示在这里...',
        querySql: '',
        queryName: '',
        table: {
          columns: ['表格结果'],
          rows: [['查询到的表格结果将显示在这里...']]
        }
      };
      from.value.query = '';
      canSave.value = false;
    }
  }).catch(err => {
    console.error('Failed to delete query record:', err);
  });
};

onMounted(() => {
  // 初始化时加载查询记录
  loadQueryRecord();
});

</script>

<template>
<div class="database-agent">
  <div class="agent-header">
    <img :src="agent.icon" alt="Agent Icon" class="agent-icon">
    <div class="agent-info">
      <div class="agent-name">{{ agent.name }}</div>
      <div class="agent-note">{{ agent.note }}</div>
    </div>
    <div class="agent-setting" @click="showSetting = true">配置</div>
  </div>
  <div class="agent-workspace">
    <div class="from query">
      <div class="from-label">查询内容</div>
      <div class="from-input">
        <input type="text" placeholder="请输入你要查询的内容,比如 '今天新增了哪些人员?'" v-model="from.query"/>
      </div>
      <button class="from-submit" @click="executeQuery(false)">查询</button>
    </div>
    <div class="result">
      <div class="history-querys">
        <div class="history-query-item" v-for="(record, index) in records" :key="record.id" @click="selectQueryRecord(record)" :class="{active: result.id === record.id}">
          <div class="left-query-text">
            <span class="query-text">{{record.queryName}}</span>
            <span class="query-time">{{record.createTime}}</span>
          </div>
          <div class="right-query-delete" @click.stop="deleteQueryRecord(record)">删除</div>
        </div>
      </div>
      <div class="tabs">
        <div class="tab-tops">
          <div class="tab-items">
            <div class="tab-item" style="border-radius: 5px 0 0 0" @click="showTab = 'text'" :class="{active: showTab === 'text'}">文字总结</div>
            <div class="tab-item" style="border-radius: 0 5px 0 0" @click="showTab = 'table'" :class="{active: showTab === 'table'}">表格结果</div>
          </div>
          <div class="tab-tools-btns">
            <button class="tab-tool-btn" :disabled="!canSave" @click="saveQuery">保存</button>
            <button class="tab-tool-btn" :disabled="!canSave" @click="() => {executeQuery(true)}">刷新</button>
          </div>
        </div>
        <div class="tab-content">
          <div class="result-content" :class="{ active: showTab === 'text' }">
            <div class="result-content-think" v-if="result.think">
              <div class="result-content-think-title">{{resultStatus === 'think' ? '正在思考并分析数据, 请稍后...' : '分析完成'}}</div>
              {{result.think}}
            </div>
            <md-preview :model-value="result.text" :codeFoldable="false"/>
          </div>
          <div class="result-content" style="padding: 0" :class="{ active: showTab === 'table' }">
            <table>
              <thead>
                <tr>
                  <th v-for="column in result.table.columns" :key="column">{{column}}</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(row, index) in result.table.rows" :key="index">
                  <td v-for="(item, rowIndex) in row" :key="rowIndex">{{item}}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  </div>

  <dialog-box v-model:show="showSetting" @close="showSetting = false" @submit="() => {databaseSettingRef.saveConfig().then(res => {
    showSetting = false;
  })}" title="配置数据库代理">
    <agent-database-setting :agent="agent" ref="databaseSettingRef"></agent-database-setting>
  </dialog-box>
</div>
</template>

<style scoped lang="less">
.database-agent{
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #fff;

  .agent-header{
    display: flex;
    align-items: center;
    padding: 10px;
    border-bottom: 1px solid #e4e4e4;

    .agent-icon {
      width: 50px;
      height: 50px;
      border-radius: 50%;
      margin-right: 15px;
    }

    .agent-info {
      flex: 1;
      .agent-name {
        font-size: 18px;
        font-weight: bold;
      }
      .agent-note {
        font-size: 14px;
        color: #666;
      }
    }
    .agent-setting{
      padding: 5px 10px;
      background-color: #f0f0f0;
      border-radius: 5px;
      cursor: pointer;
      &:hover {
        background-color: #e0e0e0;
      }
    }
  }

  .agent-workspace{
    flex: 1;
    padding: 20px;
    display: flex;
    flex-direction: column;

    .from {
      margin-bottom: 20px;
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: space-between;
      width: 100%;


      &.query {
        .from-label {
          font-size: 16px;
        }

        .from-input {
          flex: 1;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 10px;
          margin-left: 10px;

          input {
            width: calc(100% - 20px);
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 5px;
            outline: none;
          }
        }

        .from-submit {
          padding: 10px 15px;
          background-color: #007bff;
          color: white;
          border: none;
          border-radius: 5px;
          cursor: pointer;

          &:hover {
            background-color: #0056b3;
          }
        }
      }
    }

    .result{
      flex: 1;
      display: flex;
      flex-direction: row;
      gap: 20px;
      height: 100%;

      .history-querys {
        width: 250px;
        max-height: calc(100vh - 210px);
        overflow-y: auto;

        .history-query-item {
          display: flex;
          flex-direction: row;
          padding: 10px;
          border: 1px solid #e4e4e4;
          border-radius: 5px;
          margin-bottom: 10px;
          cursor: pointer;
          align-items: center;
          justify-content: space-between;

          &:hover {
            background-color: #f9f9f9;
          }
          &.active {
            border: 1px solid #007bff;
          }
          .right-query-delete {
            margin-left: 10px;
            color: #ff4d4f;
            cursor: pointer;
            &:hover {
              color: #d9363e;
            }
          }
          .left-query-text {
            flex: 1;
            display: flex;
            flex-direction: column;
            overflow: hidden;

            .query-text {
              font-size: 16px;
              color: #333;
              text-overflow: ellipsis;
              overflow: hidden;
              white-space: nowrap;
            }

            .query-time {
              font-size: 14px;
              color: #999;
            }
          }
        }
      }

      .tabs {
        flex: 1;
        display: flex;
        flex-direction: column;
        height: 100%;

        .tab-tops{
          display: flex;
          align-items: center;
          justify-content: space-between;

          .tab-items {
            display: flex;

            .tab-item {
              padding: 6px 15px;
              cursor: pointer;
              background-color: #f0f0f0;
              overflow: hidden;

              &.active {
                background-color: #007bff;
                color: white;
              }
            }
          }

          .tab-tools-btns {
            display: flex;
            gap: 10px;

            .tab-tool-btn {
              padding: 6px 12px;
              background-color: #f0f0f0;
              border: none;
              border-radius: 5px;
              cursor: pointer;

              &:hover {
                background-color: #e0e0e0;
              }

              &:disabled {
                background-color: #ccc;
                cursor: not-allowed;
              }
            }
          }
        }

        .tab-content {
          flex: 1;
          border: 1px solid #f0f0f0;
          border-radius: 0 5px 5px 5px;
          overflow: hidden;

          .result-content {
            display: none;
            padding: 10px;
            overflow-y: auto;
            max-height: calc(100vh - 235px);

            .result-content-think{
              margin-bottom: 10px;
              font-style: italic;
              color: #666;
              font-size: 12px;
              border-radius: 8px;
              box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
              padding: 10px;
              background-color: #f9f9f9;

              .result-content-think-title {
                font-weight: bold;
                color: #333;
                font-size: 16px;
                border-bottom: 1px solid #e4e4e4;
                margin-bottom: 10px;
              }

            }

            table {
              width: 100%;
              border-collapse: collapse;

              th, td {
                padding: 8px;
                text-align: left;
                border-bottom: 1px solid #ddd;
              }

              th {
                background-color: #f2f2f2;
              }
              tr:nth-child(even) {
                background-color: #fafafa;
              }
              tr:hover {
                background-color: #f1f1f1;
              }


            }

            &.active {
              display: block;
            }
          }
        }
      }
    }
  }
}
</style>
